<?php

namespace app\admin\controller\mall;

use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\MallManager;
use app\common\model\MallManagerDoor;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Validate;
/**
 * @ControllerAnnotation(title="门店管理")
 */
class Door extends AdminController
{
    use Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model =(new MallManagerDoor());
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        $manager_id =$this->request->param('id',0,'intval');
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            if($manager_id>0){
                $where[] =[['manager_id','=',$manager_id]];
            }
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            foreach ($list as $k=>$v){
                $minfo =(new MallManager())->where([['id','=',$v['manager_id']]])->find();
                $list[$k]['manager_id'] =!empty($minfo)? $minfo['title']:'';
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $managerLists =(new MallManager())->field('id,title')->where([['status','=',1]])->select()->toArray();
        $managerList = array_column($managerLists,'title','id');
        $this->assign('managerlist', json_encode($managerList));
        $this->assign('ids', $manager_id);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add($id)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new Validate();
            $validate->rule([
                'province|请选择省'  => 'require',
                'city|请选择市'  => 'require',
                'county|请选择区'  => 'require',
                'location|请选择位置'  => 'require',
                'store_no|请填写详细地址'  => 'require',
            ]);
            if(!$validate->check($post)){
                //打印错误规则，并返回页
                $this->error($validate->getError());
            }
            $rule = [];
            $this->validate($post, $rule);
            try {
                $latlng =explode(',',$post['latlng']);
                $post['lat'] =$latlng[0];
                $post['lng'] =$latlng[1];
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('ids',$id);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $validate = new Validate();
            $validate->rule([
                'province|请选择省'  => 'require',
                'city|请选择市'  => 'require',
                'county|请选择区'  => 'require',
                'location|请选择位置'  => 'require',
                'store_no|请填写详细地址'  => 'require',
            ]);
            if(!$validate->check($post)){
                //打印错误规则，并返回页
                $this->error($validate->getError());
            }
            $rule = [];
            $this->validate($post, $rule);
            try {
                $latlng =explode(',',$post['latlng']);
                $post['lat'] =$latlng[0];
                $post['lng'] =$latlng[1];
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="获取位置")
     */
    public function getRegionSearchResult(){
        $keyword =$this->request->param('keyword','','trim');
        $url="https://apis.map.qq.com/ws/place/v1/suggestion/?region=&keyword=".$keyword."&key=KQ7BZ-GAMWD-5TJ46-HST4A-H66BT-YPFCX";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        $r = curl_exec($ch);
        curl_close($ch);
        $addr = json_decode($r);
        $addresslists =[];
        if(object_array($addr)['data']){
            $addresslist =object_array($addr)['data'];
            foreach ($addresslist as $k=>$v){
                $addresslists[$k]['name'] =$v['title'];
                $addresslists[$k]['selected'] =false;
                $addresslists[$k]['disabled'] =false;
                $addresslists[$k]['value'] =$v['location']['lat'].','.$v['location']['lng'];
            }
        }

        return Show::json_show(Status::mini_normal, "ok", [
            "location" => $addresslists
        ]);
    }

    /**
     * @NodeAnotation(title="获取指定门店")
     */
    public function  getDoorByList(){
        $keyword =$this->request->param('keyword','','trim');
        $manager_id =$this->request->param('manager_id',0,'intval');
        $where =[];
        if(empty($keyword)){
            $where[] =[['title','like','%'.$keyword.'%']];
        }
        $where[] =[['manager_id','=',$manager_id]];
        $list =(new MallManagerDoor())->field('id as value,title as name')->where($where)->select()->toArray();

        return Show::json_show(Status::mini_normal, "ok", $list);
    }
}